package com.orhon.smartcampus.modules.base.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.orhon.smartcampus.utils.ObjectToMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.RegionsDao;
import com.orhon.smartcampus.modules.base.entity.Regions;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLRegion;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.RegionMapper;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class RegionsFetcher implements DataFetcher {

	@Autowired
	RegionsDao regionsDao;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {
		List<GQLRegion> GQLRegion = new ArrayList<>();

		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
		String hql = "from Regions where deleted_at = null ";
		
		if(env.containsArgument("level")) {
			int level = Integer.parseInt(env.getArgument("level").toString());
            hql += "and level " + Util.decide(level);
        }

		if(env.containsArgument("condition")) {
			HashMap<String,Object> map = ObjectToMap.to(env.getArgument("condition"));
			if(map.get("id")!=null) {
				hql += "and id " + Util.decide(map.get("id"));
			}
			if(map.get("slug")!=null) {
				hql += "and region_slug " + Util.decide(map.get("slug"));
			}
			if(map.get("name")!=null) {
				hql += "and  region_name  " + Util.decide(map.get("name"));
			}
			if(map.get("parent")!=null) {
				hql += "and parent_id "+ Util.decide(map.get("parent"));
			}
			if(map.get("level")!=null) {
				hql += "and level " + Util.decide(map.get("level"));
			}
			if(map.get("order")!=null) {
				hql += "and region_order  "+Util.decide(map.get("order"));
			}
		}
		List<Regions> list = regionsDao.find(hql,null,page.getPage(),page.getLimit());

		for (Regions r : list) {
			GQLRegion parGQLRegion = null;
			if (env.getSelectionSet().contains("data/parent")){
				Regions regions = r.getParentRegions();
				parGQLRegion = RegionMapper.MAPPER.toRegions(regions);
			}
			GQLRegion gqlRegion = RegionMapper.MAPPER.toRegions(r);
			gqlRegion.setParent(parGQLRegion);
			GQLRegion.add(gqlRegion);
		}

		Long total = 0L;
		if (env.getSelectionSet().contains("total")){
			total = regionsDao.getTotalCount(hql);
		}
		return Result.ok().put("data", GQLRegion).put("total", total);
	}


}
